#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using std::cerr;
using std::cout;
using std::endl;
using std::fstream;
using std::ifstream;
using std::ofstream;
using std::string;
using std::vector;
struct Record
{
    string _word;
    int _frequency;
} R;
class Dictionary
{
public:
    void read(const std::string &filename);
    void store(const std::string &filename);

private:
    vector<Record> _dict;
};
void Dictionary::read(const std::string &filename)
{
    // 文件输入流从外存文件流向内存的数据
    ifstream ifs(filename);
    if (!ifs.good())
    {
        cerr << "ifstream is not good" << endl;
        return;
    }
    string sentence;
    while (getline(ifs, sentence))
    {
        // 整行读取文本信息
        string word;
        for (auto &ch : sentence)
        {
            if (isalpha(ch))
            {
                word += ch;
            }
            else if (!word.empty())
            {
                // 遇到非字母字符，并且word不为空
                bool found = false;
                for (auto &record : _dict)
                {
                    if (record._word == word)
                    {
                        record._frequency++;
                        found = true;
                        break;
                    }
                }
                if(!found){
                    _dict.push_back({word,1});
                }
                word.clear();
            }
        }
        // 处理最后一个字符
        if (!word.empty())
        {
            bool found = false;
            for (auto &record : _dict)
            {
                if (record._word == word)
                {
                    record._frequency++;
                    found = true;
                    break;
                }
            }
            if(!found){
                _dict.push_back({word,1});
            }
            word.clear();
        }
    }
}

void Dictionary::store(const std::string &filename)
{
    ofstream ofs(filename);
    if (!ofs.good())
    {
        cerr << "fs is not good" << endl;
        return;
    }
    for (const auto &record : _dict)
    {
        ofs << record._word << " " << record._frequency << endl;
    }
    ofs.close();
    cout << "结果保存到" << filename << endl;
}
void test()
{
    Dictionary dict;
    dict.read("The_Holy_Bible2.txt");
    dict.store("count.txt");
}
int main()
{
    test();
    return 0;
}
